import { defineStore } from "pinia";
import { getLogin, reqUserinfo, reqLogout } from "@/api/business/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { constantRoutes } from "@/router";
import router from "@/router";
import { LoginData, TokenInfo } from "@/api/business/user/types";
import { store } from "@/store";

import { useStorage } from "@vueuse/core";

export const useUserStore = defineStore("user", () => {
  const permissionStore = usePermissionStoreHook();
  // 用户token
  const pinia_token = useStorage("pinia_token", "");
  // 用户基础、角色信息
  const pinia_userInfo = ref({
    baseInfo: {},
    roleInfo: [],
  });

  // 设置token
  function setToken(val: string) {
    pinia_token.value = val;
  }
  function setUserInfo(val: TokenInfo) {
    pinia_userInfo.value.baseInfo = val.base;
    pinia_userInfo.value.roleInfo = val.role;
  }

  // 登录
  function login(loginData: LoginData) {
    return new Promise((resolve, reject) => {
      getLogin(loginData).then((res) => {
        if (res.code == 1) {
          setToken(res.data.token);
          // ElMessage.success("登录成功");
          resolve(true);
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、路由信息集合)
  function getUserInfo() {
    return new Promise((resolve, reject) => {
      reqUserinfo().then(async (res) => {
        if (res.code == 1) {
          setUserInfo(res.data);
          const rolesList = res.data.role.map((el) => el.id);
          resolve(rolesList);
        } else {
          ElMessage.info(res.msg);
          resetStore();
        }
      });
    });
  }

  // user 登出
  function logout() {
    reqLogout().then((res) => {
      if (res.code == 1) {
        ElMessage.success("退出中...");
        setTimeout(() => {
          resetStore();
        }, 500);
      }
    });
  }

  // 清空缓存
  function resetStore() {
    location.reload(); // 清空路由
    pinia_token.value = "";
    permissionStore.pinia_menuList = constantRoutes;
    Object.assign(pinia_userInfo, { baseInfo: {}, roleInfo: [] });
  }

  return {
    pinia_token,
    pinia_userInfo,
    login,
    getUserInfo,
    logout,
    setToken,
    resetStore,
    setUserInfo,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
